//
//  QiMingAdxPrivacyViewController.m
//  QiMingADXSDKDemo
//
//  Created by Leaves on 2025/1/2.
//

#import "QiMingAdxPrivacyViewController.h"
#import <WebKit/WebKit.h>

#define QMAdxStatusBarHeight [UIApplication sharedApplication].statusBarFrame.size.height
#define QMAdxNavigationHeight (QMAdxStatusBarHeight == 20 ? 64:88)

static CGFloat const progressViewHeight = 1;

@interface QiMingAdxPrivacyViewController () <WKNavigationDelegate,WKUIDelegate>

@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation QiMingAdxPrivacyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"隐私协议";
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
}

- (void)setupUI {
    
    [self.view addSubview:self.wkWebView];
    [self.view addSubview:self.progressView];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(clickLeftItem)];
    
    if (@available(iOS 11.0, *)) {
         self.wkWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
//    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
    [self loadLocalHtml];
}

- (void)loadLocalHtml {
    // 获取 HTML 文件的路径
    NSString *htmlFilePath = [[NSBundle mainBundle] pathForResource:@"SDK_Policy" ofType:@"html"];
    NSURL *htmlFileURL = [NSURL fileURLWithPath:htmlFilePath];
        
    // 加载 HTML 文件
    [self.wkWebView loadFileURL:htmlFileURL allowingReadAccessToURL:htmlFileURL];
}

- (void)clickLeftItem {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {

}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {

}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {

}
    
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if (![scheme hasPrefix:@"http"] && [[UIApplication sharedApplication] canOpenURL:URL]) {
        if (@available(iOS 10.0, *)){
            [[UIApplication sharedApplication] openURL:URL options:@{UIApplicationOpenURLOptionsSourceApplicationKey:@YES} completionHandler:^(BOOL success) {

            }];
        } else {
            [[UIApplication sharedApplication] openURL:URL];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.wkWebView) {
        self.progressView.alpha = 1.0;
        BOOL animated = self.wkWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.wkWebView.estimatedProgress animated:animated];
        if(self.wkWebView.estimatedProgress >= 0.97) {
            [UIView animateWithDuration:0.1 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.progressView.alpha = 0.0;
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0 animated:NO];
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


#pragma mark - Lazy
- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, QMAdxNavigationHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - QMAdxNavigationHeight)];
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
        [_wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _wkWebView;
}


- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.trackTintColor = [UIColor clearColor];
        _progressView.tintColor = [UIColor blueColor];
        _progressView.frame = CGRectMake(0, QMAdxNavigationHeight , [UIScreen mainScreen].bounds.size.width, progressViewHeight);
    }
    return _progressView;
}

- (void)dealloc {
    [_wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}


@end
